# -*- coding: utf-8 -*-

"""fuwa apply controller"""
from framework.admincontroller import AdminController
from models.apply import ApplyModel
import tornado.web
import json
import re
import time

class ApplyCtrl(AdminController):
    """action index method"""

    @tornado.web.asynchronous
    @tornado.web.authenticated
    def get(self, *args):
        """apply"""
        if not args or args[0] == '/' or (not args[0]):
            self.write_error(404)
            return
        elif args[0] == '/user' or args[0] == '/user/':
            self.render('apply/user.html')
        elif args[0] == '/fuwa' or args[0] == '/fuwa/':
            self.render('apply/userfuwa.html')
        elif args[0] == '/user/list' or args[0] == '/user/list/':
            self.write(json.dumps(self.get_apply_user()))
        elif args[0] == '/fuwa/list' or args[0] == '/fuwa/list/':
            self.write(json.dumps(self.get_user_fuwa()))
        else:
            self.write_error(404)
            return
        self.finish()

    def get_apply_user(self):
        """get user apply"""
        start, size, draw = self.datatablepage()
        m = ApplyModel()
        l = m.get_apply_user(start, size)
        l['draw'] = draw
        return l

    def get_user_fuwa(self):
        """get the user apply all fuwa"""
        start, size, draw = self.datatablepage()
        m = ApplyModel()
        l = m.get_user_fuwa(start, size)
        l['draw'] = draw
        return l

    def datatablepage(self):
        """bootstrap data table page"""
        start = int(self.get_argument("start", 0))
        size = int(self.get_argument("length", 0))
        draw = int(self.get_argument("draw", 1))
        if not size:
            size = 50
        return start, size, draw
